package com.zyf.cloud.services.userservice.controller;


import com.zyf.cloud.common.data.ResponseDto;
import com.zyf.cloud.common.data.StatusCodeConstants;
import com.zyf.cloud.common.utils.MD5Utils;
import com.zyf.cloud.services.userservice.config.DtoUtil;
import com.zyf.cloud.services.userservice.config.ErrorCode;
import com.zyf.cloud.services.userservice.entity.EsBlog;
import com.zyf.cloud.services.userservice.entity.UserEntity;
import com.zyf.cloud.services.userservice.service.IEsBlogService;
import com.zyf.cloud.services.userservice.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.regex.Pattern;

/**
 * @author Administrator
 * 控制层
 * 用户基本信息表
 */
@Slf4j
@RestController
@Api(tags = "用户基本信息表")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * * 测试es
     */
    @Autowired
    private IEsBlogService esBlogService;

    @GetMapping(value = "/query")
    @ApiOperation("测试es")
    public Page listBlogs(
            @RequestParam(value = "keyword", required = false, defaultValue = "") String keyword,
            @RequestParam(value = "pageIndex", required = false, defaultValue = "0") int pageIndex,
            @RequestParam(value = "pageSize", required = false, defaultValue = "5") int pageSize) {
        Pageable pageable = PageRequest.of(pageIndex, pageSize);
        Page<EsBlog> page = esBlogService.getEsBlogByKeys(keyword, pageable);
//        List<EsBlog> list  = page.getContent();
//        model.addAttribute("order", order);
//        model.addAttribute("keyword", keyword);
//        model.addAttribute("page", page);
//        model.addAttribute("blogList", list);
        return page;
    }

    @GetMapping(value = "/add")
    @ApiOperation("测试es添加")
    public Boolean testAdd(Model model) {
        Boolean ok = esBlogService.testAdd();
        return ok;
    }

    @PostMapping("upUserPassword")
    @ApiOperation("修改密码")
    //关于修改密码的表单提交
    public String upUserPassword(@RequestParam("id") String id,
                                 @RequestParam("password") String password,
                                 @RequestParam("newpassword") String newpassword) {
        if (userService.upUserPasswordRedis(Integer.parseInt(id), password, newpassword) != null) {
            log.info(password + "   " + id + "   " + newpassword);
            return "修改密码成功!";
        } else {
            return "密码错误！";
        }

    }

    @GetMapping("find")
    @ApiOperation("查找单个用户,redis缓存")
    public Object find(Integer id) {
        return userService.findUserById(id);
    }

    @GetMapping("findByToken")
    @ApiOperation("查找单个用户,redis缓存")
    public Object findByToken(String token) {
        return userService.findByToken(token);
    }

    @GetMapping("update")
    @ApiOperation("更新单个用户,redis缓存")
    public Object update(Integer id, String name) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);
        userEntity.setName(name);
        return userService.update(userEntity);
    }

    @GetMapping("delete")
    @ApiOperation("删除单个用户,redis缓存")
    public Object delete(Integer id) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);
        userService.deleteById(userEntity);
        return "移除缓存 key = " + id;
    }

    @GetMapping("deleteAll")
    @ApiOperation("删除所有用户,redis缓存")
    public Object deleteAll(@RequestBody Integer id) {
        userService.deleteById(id);
        return "移除所有缓存";
    }

    /**
     * * 测试
     */
    @GetMapping("/cs")
    @ApiOperation(value = "测试")
    public String cha() {
        String a = "zhang";
        String c = "fei";

//        log.debug("bbb");
//        log.info("ccc");
//        log.trace("ddd");
//        log.warn("fff");
//        log.error("ppp");
        log.info("输入参数信息a={},c={}", a, c);
        return "templates/user/login";
    }

    /**
     * * 注册
     */
    @PostMapping("regist")
    @ApiOperation(value = "注册")
    public int regist2(@RequestBody UserEntity userEntity, Model model) {
        int findUserByLgName = userService.findUserByLgName(userEntity.getName());
        int message;
        if (userEntity.getName().length() == 0 || userEntity.getPassword().length() == 0) {
            message = -1;
            log.info("用户信息输入信息有误");
        } else if (findUserByLgName == 0) {
            userService.regist2(userEntity);
            message = 1;
            log.info("注册成功");
        } else {
            log.info("用户存在");
            message = 0;
        }
        return message;
    }

    @PostMapping("login")
    @ApiOperation(value = "登入")
    public String login(@RequestParam("name") String name, @RequestParam("password") String password, Model model) {
        UserEntity user = new UserEntity();
        user.setName(name);
        user.setPassword(password);
        UserEntity isLogin = userService.login(name, password);
        if (isLogin != null) {
            return "templates/user/login.html";
        } else {
            return "登入失败";
        }
    }

    @PostMapping("api_login")
    @ApiOperation(value = "api登入")
    public ResponseDto apiLogin(@RequestParam("name") String name, @RequestParam("password") String password) {
        System.out.println("用户登录：" + name + password);

        System.out.println(MD5Utils.MD5(String.valueOf(1)));
        UserEntity userEntity = userService.login(name, password);
        if (ObjectUtils.isEmpty(userEntity)) {
            return new ResponseDto(StatusCodeConstants.ERROR, "登录失败,用户名或密码错误", null);
        }
        String token = "";
        String tokenRefresh = "";
        return new ResponseDto(StatusCodeConstants.SUCCESS, "登录成功", token, tokenRefresh);
    }

    @PostMapping(value = "/selectById")
    @ApiOperation(value = "根据id查询客户信息")
    public Object getCustomerById(@RequestParam("id") Integer id) {
        System.out.println("查询：" + id);
        return userService.selectById(id);
    }

    @PostMapping("/updateById")
    @ApiOperation(value = "根据id修改客户信息")
    public Object update(@RequestBody UserEntity user) {
//        if (!userService.isUserExist(id)) {
//            return "用户不存在！";
//        } else {
//            userService.update(user);
//            return "修改密码成功!";
//        }
        userService.update(user);
        return "修改密码成功!";
    }

    @PostMapping("/deleteById")
    @ApiOperation(value = "根据id删除用户,物理删除")
    public Object deleteById(@RequestParam("id") Integer id) {
        System.out.println("删除：" + id);
        userService.deleteById(id);
        return "删除成功";
    }

    @PostMapping("/testTrans")
    @ApiOperation(value = "根据id删除用户,物理删除")
    public Object testTrans() {
        userService.testTrans();
        return "删除成功";
    }

    /**
     * 使用邮箱注册
     *
     * @param userVO
     */
//    @ApiOperation(value = "使用邮箱注册", httpMethod = "POST",
//            protocols = "HTTP")
//    @RequestMapping(value = "/yx", method = RequestMethod.POST)
//    @ResponseBody
    @PostMapping("/yxzc")
    @ApiOperation(value = "邮箱注册")
    public Object doRegister(@RequestBody UserEntity userVO) {
        if (!validEmail(userVO.getEmail())) {
            return DtoUtil.returnFail("请使用正确的邮箱地址注册", ErrorCode.AUTH_ILLEGAL_USERCODE);
        }
        try {

            //用户唯一性验证
            if (null == userService.findByUsername(userVO.getName())) {
                UserEntity user = new UserEntity();
                user.setEmail(userVO.getEmail());
                user.setPhoneNumber(userVO.getPhoneNumber());
                user.setPassword(MD5Utils.getMd5(userVO.getPassword(), 32));
                user.setName(userVO.getName());
                userService.insertUser(user);
                return DtoUtil.returnSuccess();
            } else {
                System.out.println(userVO.getName());
                return DtoUtil.returnFail("用户已存在，注册失败", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email) {
        String regex = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();
    }

}


